package com.example.itces.controller;

import com.example.itces.domain.User;
import com.example.itces.service.UserService;
import com.example.itces.utils.RandomValidateCodeUtil;
import com.example.itces.utils.ResponData;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;

@Controller
public class UserController {

    @Autowired
    UserService userService;


    /**
     * 用户登陆
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public ResponData UserLogin(@PathParam("username") String username,
                                @PathParam("password") String password,
                                @PathParam("validate") String validate,
                                HttpSession session){
        String session_validate= (String) session.getAttribute("validate");
        if(validate.equals(session_validate)){
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            Subject subject = SecurityUtils.getSubject();
            token.setRememberMe(true);
            try {
                subject.login(token);
                return ResponData.build(1,"index");
//            session.setAttribute("user", subject.getPrincipal());
            } catch (Exception e) {
                return ResponData.build(0,null);
            }
        }else {
            return ResponData.build(2,"验证码不正确");
        }
    }


    /**
     * 用户注册
     * @param user 用户信息
     * @param viladate 验证码
     * @param session session
     * @return
     */
    @RequestMapping(value = "register",method = RequestMethod.POST)
    @ResponseBody
    public ResponData UserRegister(User user,
                                   @RequestParam String viladate,
                                   HttpSession session){
        String session_validate= (String) session.getAttribute("validate");
        if(viladate.equals(session_validate)){
            int i = userService.UserRegister(user);
            if (i > 0){
                System.out.println("用户创建成功");
                return ResponData.build(1,"login");
            }else {
                System.out.println("用户创建失败");
                return ResponData.build(0,"用户创建失败");
            }
        }else {
            return ResponData.build(0,"验证码不正确");
        }
    }

    /**
     * 用户注册时查库看用户名是否存在
     * @param username 用户名
     * @return
     */
    @RequestMapping("/selectbyname")
    @ResponseBody
    public ResponData selectByName(@PathParam("username") String username){

        Boolean aBoolean = userService.selectByName(username);

        if (aBoolean!=null){
            return ResponData.build(0,"用户名已注册");
        }else {
            return ResponData.build(1,"用户名可用");
        }
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            System.out.println("获取验证码失败>>>>   "+e);
        }
    }

    @RequestMapping("/checklogin")
    @ResponseBody
    public ResponData checkloginstate(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user!=null){
            return ResponData.build(1,user.getName(),user.getRole().toString());
        }else return ResponData.build(0,null);
    }

    @RequestMapping("/page/user/getUserInformation")
    @ResponseBody
    public ResponData getUserInformation(HttpSession session){
        User user=(User) SecurityUtils.getSubject().getPrincipal();
        user.setPassword(null);
        return ResponData.ok(user);
    }
}
